<template>
  <!-- 生产作业配置 -->
  <BaseMainSlot :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        :has-save="false"
        :has-del="false"
        @add="add"
        @cancel="cancel"
        @del="del"
        @edit="edit"
        @save="save"
      />
    </template>
    <template v-slot:tab-select>
      <SelectButton :buttonselectlist="buttonselectlist" @nowselectbuttonindex="batchstaumet" />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label">作业名称:</div>
          <div class="input">
            <el-input v-model="searchForm.svcClassName" clearable @keyup.enter.native="search" @blur="search" @clear="search" />
          </div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <!-- 业务组件展示表格 -->
      <div class="zh-table-view">
        <div class="card" v-for="item,index in tableData" :key="index">
          <div class="title">
            {{ item.svcClassName || '收割作业信息' }}
            <div class="btn-operate">
              <div class="btn" @click="handleEdit(item)">
                <i class="el-icon-edit"></i>
                修改
              </div>
              <div class="btn" @click="dellineallmes(item)">
                <i class="el-icon-delete"></i>
                删除
              </div>
            </div>
          </div>
          <div class="field-list">
            <div class="field" v-for="it,i in item.classPropertyList" :key="i">
              <div class="info">字段{{ i+1 }}名称：{{ it.propertyName }}</div>
              <div class="info">字段类型：{{ getType(it.propertyType) }}</div>
            </div>
          </div>
        </div>
        <div class="nodata" v-if="tableData.length == 0">暂无数据</div>
      </div>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <!-- 新增作业 -->
      <el-dialog
        :title="titleText + '作业'"
        class="formData"
        :visible.sync="dialogFormVisible"
        width="35%"
        top="5vh"
        :before-close="() => { cancel() }"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="作业名称:" prop="svcClassName" class="field-box w100p">
            <el-input v-model="formData.svcClassName" clearable />
            <!-- <i class="add el-icon-circle-plus-outline" @click="addField"></i> -->
          </el-form-item>
          <el-form-item label="自定义字段:" class="field-box w100p">
            <i class="el-icon-circle-plus-outline" @click="addField"></i>
          </el-form-item>
          <div class="field-box" v-for="item,i in fieldList" :key="item.id">
            <el-form-item :label="`字段${i+1}名称:`" :prop="`field${item.id}`" class="w100p"
              :rules="[{
                required: true,
                message: `字段${i+1}名称不能为空`,
                trigger: ['change', 'blur'],
              }]">
              <el-input v-model="formData[`field${item.id}`]" clearable />
            </el-form-item>
            <el-form-item label="是否必填:" :prop="`required${item.id}`" class="w100p"
              :rules="[{
                required: true,
                message: `是否必填不能为空`,
                trigger: ['change', 'blur'],
              }]">
              <el-select v-model="formData[`required${item.id}`]" placeholder="请选择">
                <el-option label="是" :value="true"></el-option>
                <el-option label="否" :value="false"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="字段类型:" :prop="`type${item.id}`" class="w100p"
              :rules="[{
                required: true,
                message: `字段类型不能为空`,
                trigger: ['change', 'blur'],
              }]">
              <el-select v-model="formData[`type${item.id}`]" placeholder="请选择">
                <el-option label="字符" :value="1"></el-option>
                <el-option label="数字" :value="2"></el-option>
                <el-option label="日期" :value="4"></el-option>
              </el-select>
            </el-form-item>
            <i class="delete el-icon-circle-close" @click="removeField(i)"></i>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel()">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import ActionBar from "@/components/ActionBar/index";
import { mymixin } from "@/utils/mixins";
import SearchBox from "@/components/SearchBox";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import axios from "axios";
import Pagination from "@/components/Pagination";
import SelectButton from "@/components/SelectButton";
import { getToken } from '@/utils/auth'

export default {
  components: { ActionBar, BaseMainSlot, Pagination, SearchBox, SelectButton },
  mixins: [mymixin],
  data() {
    return {
      farming: 'FISH',
      buttonselectlist: [
        { name: '水产', value: 'FISH' },
        { name: '畜牧', value: 'BREED' },
        { name: '种植', value: 'PLANT' },
      ],
      tableData: [],
      pageSize: 10,
      currentPage: 1,
      totalSize: 0,
      databaseName: 'DB_TDW1_PUBLIC',
      // ---添加相关---
      formData: {},
      fieldList: [],
      searchForm: {},
      rules: {
        svcClassName: [{ required: true, message: "请输入作业名称", trigger: "blur" }],
      }
    };
  },
  watch: {
    dialogFormVisible: {
      handler (v) {
        if (this.nowChanceStau == 'add') {
          this.fieldList = []
        }
        this.$nextTick(() => {
          this.$refs.formData && this.$refs.formData.clearValidate();
        })
      },
      immediate: true,
      deep: true
    }
  },
  created() {
  },
  mounted () {
    this.gettabledataList()
  },
  methods: {
    batchstaumet(item, i) {
      this.farming = item.value;
      this.tableData = [];
      this.gettabledataList();
    },
    // 获取表格信息
    async gettabledataList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...this.searchForm,
          businessType: 'AGRICULTURE_WORK_TYPE',
          farming: this.farming
        }
      };
      const { data: mes } = await axios({
        method: "post",
        url: this.$webSerUrlPro + 'config/serviceClass/queryPageList',
        headers: {
          databaseName: this.databaseName
        },
        data: params
      })
      if (mes.code === 1) {
        this.tableData = mes.data.content || []
        this.totalSize = mes.data.totalElements
        this.resetActionBar()
      } else {
        this.$message.warning("获取表格失败")
      }
    },
    handleSelectionChange() {
      this.nowselectedList = [];
      const list = this.$refs.catetreetwo.getCheckedNodes();
      this.nowselectedList = list.map((item) => {
        return item.id;
      });
      if (this.nowselectedList && this.nowselectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    // 搜索
    search() {
      this.currentPage = 1;
      this.gettabledataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.gettabledataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.gettabledataList();
    },
    // 添加字段
    addField () {
      let len = this.fieldList.length
      let id = len ? this.fieldList[len-1].id + 1 : 1
      this.$set(this.fieldList, len, { id })
      this.$nextTick(() => {
        this.$refs.formData && this.$refs.formData.clearValidate();
      })
    },
    removeField (i) {
      this.fieldList.splice(i, 1)
    },
    // 修改
    handleEdit(row) {
      if (row) {
        this.formData = { ...row };
        let fieldList = []
        if (row.classPropertyList) {
          row.classPropertyList.map((el, i) => {
            let id = i + 1
            fieldList.push({ id, propertyId: el.id })
            this.$set(this.formData, `field${id}`, el.propertyName)
            this.$set(this.formData, `required${id}`, el.required)
            this.$set(this.formData, `type${id}`, el.propertyType)
          })
          this.fieldList = fieldList
        } else {
          this.fieldList = []
        }
      }
      this.edit()
    },
    // 删除一个业务组件
    dellineallmes(e) {
      this.$confirm('此操作将删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios({
          method: 'delete',
          url: this.$webSerUrlPro + 'config/serviceClass/del?id='+e.id,
          headers: {
            databaseName: this.databaseName
          }
        }).then(res => {
          if (res.data.code === 1) {
            this.$message.success("删除成功！")
            this.gettabledataList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 保存要添加的业务的组件信息
    save() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          let classPropertyList = []
          this.fieldList.map(el => {
            let obj = {
              propertyName: this.formData[`field${el.id}`],
              required: this.formData[`required${el.id}`],
              propertyType: this.formData[`type${el.id}`]
            }
            el.propertyId && (obj.id = el.propertyId)
            classPropertyList.push(obj)
          })
          let param = {
            svcClassName: this.formData.svcClassName,
            businessType: 'AGRICULTURE_WORK_TYPE',
            classPropertyList,
            farming: this.farming
          };
          if (this.nowChanceStau === "edit") {
            param.id = this.formData.id
            axios({
              method: "put",
              url: this.$webSerUrlPro + 'config/serviceClass/edit',
              headers: {
                databaseName: this.databaseName
              },
              data: param
            }).then(res => {
              if (res.data.code === 1) {
                this.$message.success("修改成功！")
                this.gettabledataList()
                this.dialogFormVisible = false
              } else {
                this.$message.error(res.data.msg)
              }
            })
          } else if (this.nowChanceStau === "add") {
            axios({
              method: "post",
              url: this.$webSerUrlPro + 'config/serviceClass/add',
              headers: {
                databaseName: this.databaseName
              },
              data: param
            }).then(res => {
              if (res.data.code === 1) {
                this.$message.success("添加成功！")
                this.gettabledataList()
                this.dialogFormVisible = false
              } else {
                this.$message.error(res.data.msg)
              }
            })
          }
        } else {
          return false;
        }
      });
    },
    getType (type) {
      if (type == 1) return '字符'
      if (type == 2) return '数字'
      if (type == 4) return '日期'
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.zh-table-view{
  width: 100%;
  height: calc(100% - 60px);
  position: relative;
  overflow: hidden auto;
  .card {
    width: 100%;
    height: fit-content;
    margin-top: 15px;
    background: #00171c;
    border-radius: 5px;
    overflow: hidden;
    .title {
      font-size: 18px;
      padding: 10px 15px;
      background: #0091b7;
      position: relative;
      .btn-operate {
        position: absolute;
        right: 15px;
        top: 10px;
        .btn {
          display: inline-block;
          margin-right: 15px;
          font-size: 14px;
          cursor: pointer;
          &:last-child {
            margin-right: 0;
            color: red;
          }
        }
      }
    }
    .field-list {
      padding: 15px 15px 20px;
      .field {
        display: inline-block;
        width: calc(33% - 10px);
        margin-right: 10px;
        &:last-child {
          margin-right: 0;
        }
        .info {
          display: inline-block;
          &:first-child {
            margin-right: 30px;
          }
        }
      }
    }
  }
  .nodata {
    width: 100%;
    font-size: 18px;
    padding-top: 30px;
    text-align: center;
  }
}
::v-deep {
  .el-dialog {
    min-width: 35% !important;
    .el-dialog__body {
      padding: 30px 80px 20px 50px;
    }
  }
}
.field-box {
  width: 100%;
  position: relative;
  .add, .delete {
    position: absolute;
    top: 4px;
    right: -40px;
    font-size: 30px;
    cursor: pointer;
  }
  .el-icon-circle-plus-outline {
    font-size: 30px;
    cursor: pointer;
  }
}
.search-list {
  .common-search-item {
    .label {
      min-width: 80px !important;
      text-align: right;
    }
  }
}
</style>
